package com.aikon.wht.java8;

import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import com.sun.org.apache.xpath.internal.SourceTree;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author haitao.wang
 */
public class TestOfJava8 {

    public static void main(String[] args) {
        Collection<Order> orders = new ArrayList<>();
        orders.add(new Order<>(Lists.newArrayList("a", "b", "c")));
        orders.add(new Order<>(Lists.newArrayList("d", "h", "c")));
        orders.add(new Order<>(Lists.newArrayList("e", "i", "c")));
        orders.add(new Order<>(Lists.newArrayList("f", "j", "c")));



        List<List<String>> ts = Lists.newArrayList();
        ts.add(Lists.newArrayList("a", "b", "c"));
        ts.add(Lists.newArrayList("d", "h", "c"));
        ts.add(Lists.newArrayList("e", "i", "c"));
        ts.add(Lists.newArrayList("f", "j", "c"));

        List<Person> ps = Lists.newArrayList(new Person(1,"xx"),new Person(2,"yy"),new Person(3,"zz"));
        // flatMap map
        List<String> ss = ts.stream().flatMap(t -> t.stream().map(i -> i + "xx")).collect(Collectors.toList());

        System.out.println(ss);
        Stream.of(ss).peek(t -> System.out.println(t)).collect(Collectors.toList());
        Stream.generate(new Random()::nextInt).limit(5).forEach(System.out::println);
        // implement Supplier
        Stream.generate(() -> "a").limit(5).forEach(System.out::println);
        Stream.iterate(2, n -> n*n).limit(5).forEach(System.out::println);
        Map<Integer,List<Person>> pm = ps.stream().collect(Collectors.groupingBy(Person::getAge));
        // Not able to handle duplicate key or null value unless implement collectors yourself
//        Map<Integer,Person> pmm = ps.stream().collect(Collectors.toMap(Person::getAge, (p) -> p));
//        System.out.println(pmm);
        Map<Integer,Person> pmmm = Maps.uniqueIndex(ps, p -> p.getAge());

        ps.stream().sorted((o1, o2) -> o1.getAge() - o2.getAge()).peek(System.out::print).filter(i -> i.getAge() < 3).forEach(i -> i.setName(i.getName() + "QQ"));
        System.out.println("xxxsssssssssssssssssssss");
        System.out.println(ps);
        System.out.println(ps.stream().anyMatch(i->i.getAge()==1));

    }

    public static class Order<T> {
        Collection<T> types;

        public Order(Collection<T> types) {
            this.types = types;
        }

        public Collection<T> getTypes() {
            return types;
        }

        public void setTypes(Collection<T> types) {
            this.types = types;
        }
    }

}
